import React, {useContext} from 'react';
import { LedgerContext } from '../Ledger';

import './book-manager.css';

export default () => {

  const {books, switchBook} = useContext(LedgerContext);
  
  const groupedBooks = {};
  for (let book of books) {
    const cate = book.cate ?? '默认';
    groupedBooks[cate] ?? (groupedBooks[cate] = []);
    if (!book.hide) {
      const {name, desc, descAddi} = book;
      groupedBooks[cate].push(
      <div className='list-group-item list-group-item-action book-item' key={`list-${name}`} onClick={() => switchBook({name})}>
        <div style={{whiteSpace:'pre-wrap'}}>{desc}</div>
        <small className="form-text text-muted">{descAddi ?? name}</small>
      </div>)
    }
  }

  const groups = Object.entries(groupedBooks).map(([cateName, books]) => {
    return <div className='list-group' key={`cate-${cateName}`}>
      <div key={`cate-${cateName}`} className='text-muted' style={{padding: '15px 5px 5px'}}>{cateName}</div> 
      {books}
    </div>
  })

  return <div style={{height:'100%', width: '300px', minWidth: '300px', background:'lightgray', padding: '10px'}}>
    {groups}
  </div>

}
